﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class BaseDAL<T> where T : class
    {
        /// <summary>
        /// 依赖注入HospitalDbContext
        /// </summary>
        HospitalDbContext db;

        public BaseDAL(HospitalDbContext db)
        {
            this.db = db;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity">添加实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> Addasync(T entity)
        {
            try
            {
                await db.Set<T>().AddAsync(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 无条件查询
        /// </summary>
        /// <returns>返回受影响行数</returns>
        public IQueryable<T> Query()
        {
            try
            {
                return db.Set<T>().AsQueryable();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 单条件查询
        /// </summary>
        /// <param name="expression">条件表达式</param>
        /// <returns>返回受影响行数</returns>
        public async Task<T> Getasync(Expression<Func<T,bool>> expression)
        {
            try
            {
                return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">修改实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> Updasync(T entity)
        {
            try
            {
                db.Set<T>().Update(entity);
                return await db.SaveChangesAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
